<html>
  <head></head>
  <body>
    <p>判断两个对象是否相等</p>

    <script>
      var obj1 = {
        name: 'burc',
        age: [21, 22],
      }
      var obj2 = {
        name: 'burc',
        age: [21, 22],
      }

      console.log(isEqual(obj1, obj2))

      
      function isEqual(source, target) {
        // source 为基本数据类型
        if (typeof source !== 'object' || !source) return source === target
        // target 为基本数据类型
        if (typeof target !== 'object' || !target) return target === source

        // source, target 数据类型不一致
        if (source instanceof Array !== target instanceof Array) return false

        // source, target 长度不一致
        if (source instanceof Array && source.length !== target.length) return false
        // source, target 长度不一致
        if (!source instanceof Array && Object.keys(source).length !==  Object.keys(target).length) return false

        // source, target 都为数组
        if (source instanceof Array) {
          const isAllEqual = source.every((item, index) => isEqual(item, target[index]))
          return isAllEqual
        }

        // source, target 都为对象
        for (const key in source) {
          if (Object.hasOwnProperty.call(source, key)) {
            if (!isEqual(source[key], target[key])) return false
          }
        }

        return true
      }
    </script>
  </body>
</html>
